package wellplatescanner;




public class Session {
	
	Thread workerThread;
	ArduinoDevice arduino;
	ScannerDevice scanner;
	MainWindow mainWindow;
	
	public Session(ArduinoDevice arduino, ScannerDevice scanner, MainWindow mainWindow) {
		this.arduino = arduino;
		this.scanner = scanner;
		this.mainWindow = mainWindow;
	}
	
	public void start(final Project project) {
		stop();
		
		workerThread = new Thread(new Runnable() 
		{
			@Override
			public void run() {
				int i = 0;
				
				try {
					while(true) {

						Log.println("---- Starting scanning sequence ----");

						Log.println("Stopping shake ...");
						
						// Stop arduino
						arduino.setRequestedState(ArduinoDevice.STATE_STOPPED);
						while(arduino.getState() != ArduinoDevice.STATE_STOPPED) {
							Thread.sleep(100);
						}

						Log.println("Starting scan ...");
						
						// Scan
						//mainWindow.startScan();
						scanner.aquire(project.path, project.scannerSettings);
						while(scanner.isScanning()) {
							Thread.sleep(100);
						}

						Log.println("Starting shake ...");

						// Start arduino
						arduino.setRequestedState(ArduinoDevice.STATE_SHAKING);
						while(arduino.getState() != ArduinoDevice.STATE_SHAKING) {
							Thread.sleep(100);
						}

						Log.println("Waiting for next scanning sequence ...");

						long delay = (long)(project.delay*60.0*1000.0);

						Thread.sleep(delay);
					}
				} catch (InterruptedException e) {
				}
			}
		});
		
		workerThread.start();
	}
	
	public void stop() {
		if(workerThread != null) {
			workerThread.interrupt();
			workerThread = null;
		}
	}
}
